//
//  PopAnimateInterDismiss.swift
//  UIViewDemo
//
//  Created by 劢克科技 on 2019/3/8.
//  Copyright © 2019 劢克科技. All rights reserved.
//

import UIKit

class PopAnimateInterDismiss: UIPercentDrivenInteractiveTransition {
    
    init(gesture: UIPanGestureRecognizer) {
        super.init()
        gestureRecognizer = gesture
        gestureRecognizer?.addTarget(self, action: #selector(gestureRecognizeDidUpdate(sender:)))
    }
    
    private var gestureRecognizer: UIPanGestureRecognizer?
    var startPoint: CGPoint?
    var transitionContext: UIViewControllerContextTransitioning?
    
    override func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) {
        super.startInteractiveTransition(transitionContext)
        self.transitionContext = transitionContext
    }
    
    @objc func gestureRecognizeDidUpdate(sender: UIPanGestureRecognizer) {
        let view = transitionContext?.containerView
        switch sender.state {
        case .changed:
            if startPoint == nil {
                startPoint = sender.location(in: view)
            }
            update(getPercent())
            break
        case .ended:
            if getPercent() > 0.2 {
                finish()
            } else {
                cancel()
            }
            break
        default:
            cancel()
            break
        }
    }
    
    func getPercent() -> CGFloat {
        let view = transitionContext?.containerView
        let currentPoint = gestureRecognizer?.location(in: view)
        guard let currentY = currentPoint?.y else { return 0 }
        guard let startY = startPoint?.y else {
            return 0
        }
        let moveH = currentY - startY
        let offset = UIScreen.main.bounds.height / 2
        return moveH / offset
    }
    
    deinit {
        gestureRecognizer?.removeTarget(self, action: #selector(gestureRecognizeDidUpdate(sender:)))
    }
}
